# -*- coding: utf-8 -*-
# @Time : 2025/06/16 22:44:42
# @Desc :  生成 Inno Setup 脚本
# @Author : Sean
# @File   : build.py

from getAppISSID import GetAPPISSID
from utils.common import get_root_path
from config.config import Config
from pathlib import Path
import sys

sys.path.insert(0, str(Path().absolute()))

appISSID = GetAPPISSID().APPISSID()
appName = Config.appName
appPackage = Config.appPackage
appVersion = Config.appVersion
appBlogs = Config.appHome
appDeveloper = Config.appDeveloper
appUpdateUrl = Config.appUpdateUrl
# 默认安装目录  C:\path
installDirName = ""
buildDir = str(Path(get_root_path(), "dist"))
logoPath = str(Path(buildDir, appPackage, "icon", "logo.ico"))
logoImgPath = str(Path(buildDir, appPackage, "icon", "logo.bmp"))
imgPath = str(Path(buildDir, appPackage, "icon", "topright.bmp"))


def getIss():
    iss_content = (
        '''
    ; 脚本由 Inno Setup 脚本向导 生成！
    ; 有关创建 Inno Setup 脚本文件的详细资料请查阅帮助文档！
    #define MyAppName "'''
        + appName
        + '''"
    #define MyappPackage "'''
        + appPackage
        + '''"
    #define MyAppVersion "'''
        + appVersion
        + '''"
    #define MyAppPublisher "'''
        + appDeveloper
        + '''" 
    #define MyAppURL "'''
        + appBlogs
        + '''"
    #define MyAppUpdateUrl "'''
        + appUpdateUrl
        + '''"
    #define MyAppExeName "'''
        + appPackage
        + """.exe"
    #define MyAppAssocName MyAppName + " 文件"
    #define MyAppAssocExt ".myp"
    #define MyAppAssocKey StringChange(MyAppAssocName, " ", "") + MyAppAssocExt

    [Setup]
    ; 注: AppId的值为单独标识该应用程序。
    ; 不要为其他安装程序使用相同的AppId值。
    ; (若要生成新的 GUID，可在菜单中点击 "工具|生成 GUID"。)
    AppId ="""
        + appISSID
        + '''
    AppName={#MyAppName}
    AppVersion={#MyAppVersion}
    VersionInfoVersion={#MyAppVersion}
    AppVerName={#MyAppName} {#MyAppVersion}
    AppPublisher={#MyAppPublisher}
    AppPublisherURL={#MyAppURL}
    AppSupportURL={#MyAppURL}
    AppUpdatesURL={#MyAppUpdateUrl}
    DefaultDirName={autopf}\{#MyappPackage}
    ChangesAssociations=yes
    DisableProgramGroupPage=yes
    ; 移除以下行，以在管理安装模式下运行（为所有用户安装）。
    PrivilegesRequired=lowest
    OutputDir="'''
        + str(buildDir)
        + """"
    OutputBaseFilename="""
        + appName
        + """_V"""
        + appVersion
        + '''_Windows
    SetupIconFile="'''
        + str(logoPath)
        + '''"
    Compression=lzma2/ultra64
    SolidCompression=yes
    WizardStyle=modern
    ; 164x314 pixels bmp格式必须是24位
    WizardImageFile="'''
        + str(imgPath)
        + '''"
    ; 55x58 pixels bmp格式必须是24位
    WizardSmallImageFile="'''
        + str(logoImgPath)
        + '''"
    UninstallDisplayName = "'''
        + appName
        + '''"
    UninstallDisplayIcon = "'''
        + str(logoPath)
        + '''"

    [Languages]
    Name: "chinesesimp"; MessagesFile: "compiler:Default.isl"

    [Tasks]
    Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked

    [Files]
    Source: "'''
        + str(buildDir)
        + '''\\{#MyappPackage}\\*"; DestDir: "{app}"; Flags: recursesubdirs createallsubdirs ignoreversion
    ; 注意: 不要在任何共享系统文件上使用“Flags: ignoreversion”

    [Icons]
    Name: "{autoprograms}\\{#MyAppName}"; Filename: "{app}\\{#MyAppExeName}"
    Name: "{autodesktop}\\{#MyAppName}"; Filename: "{app}\\{#MyAppExeName}"; Tasks: desktopicon

    [Registry]
    Root: HKA; Subkey: "Software\\Classes\\{#MyAppAssocExt}\\OpenWithProgids"; ValueType: string; ValueName: "{#MyAppAssocKey}"; ValueData: ""; Flags: uninsdeletevalue
    Root: HKA; Subkey: "Software\\Classes\\{#MyAppAssocKey}"; ValueType: string; ValueName: ""; ValueData: "{#MyAppAssocName}"; Flags: uninsdeletekey
    Root: HKA; Subkey: "Software\\Classes\\{#MyAppAssocKey}\\DefaultIcon"; ValueType: string; ValueName: ""; ValueData: "{app}\\{#MyAppExeName},0"
    Root: HKA; Subkey: "Software\\Classes\\{#MyAppAssocKey}\\shell\\open\\command"; ValueType: string; ValueName: ""; ValueData: """{app}\\{#MyAppExeName}"" ""%1"""
    Root: HKA; Subkey: "Software\\Classes\\Applications\\{#MyAppExeName}\\SupportedTypes"; ValueType: string; ValueName: ".myp"; ValueData: ""

    [Run]
    Filename: "{app}\\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: nowait postinstall skipifsilent

    [Code]
    // 自定义函数，判断软件是否运行，参数为需要判断的软件的exe名称
    function KDetectSoft(strExeName: String): Boolean;
    // 变量定义
    var ErrorCode: Integer;
    var bRes: Boolean;
    var strFileContent: AnsiString;
    var strTmpPath: String;  // 临时目录
    var strTmpFile: String;  // 临时文件，保存查找软件数据结果
    var strCmdFind: String;  // 查找软件命令
    var strCmdKill: String;  // 终止软件命令
    begin
    strTmpPath := GetTempDir();
    strTmpFile := Format('%sfindSoftRes.txt', [strTmpPath]);
    strCmdFind := Format('/c tasklist /nh|find /c /i "%s" > "%s"', [strExeName, strTmpFile]);
    strCmdKill := Format('/c taskkill /f /t /im %s', [strExeName]);
    bRes := ShellExec('open', ExpandConstant('{cmd}'), strCmdFind, '', SW_HIDE, ewWaitUntilTerminated, ErrorCode);
    if bRes then begin
        bRes := LoadStringFromFile(strTmpFile, strFileContent);
        strFileContent := Trim(strFileContent);
        if bRes then begin
            if StrToInt(strFileContent) > 0 then begin
                if MsgBox('软件正在运行，要自动关闭继续吗？', mbConfirmation, MB_OKCANCEL) = IDOK then begin
                // 终止程序
                ShellExec('open', ExpandConstant('{cmd}'), strCmdKill, '', SW_HIDE, ewNoWait, ErrorCode);
                Result:= true;// 继续安装
                end else begin
                Result:= false;// 安装程序退出
                Abort; // 退出整个安装程序
                end;
            end else begin
                //MsgBox('软件没在运行', mbInformation, MB_OK);
                Result:= true;
                Exit;
            end;
        end;
    end;
    Result :=true;
    end;

    // 开始页下一步时判断软件是否运行
    function NextButtonClick(CurPageID: Integer): Boolean;
    begin
    if 1=CurPageID then begin
        Result := KDetectSoft('{#MyAppExeName}');
        Exit;
    end; 
    Result:= true;
    end;

    // 初始化卸载时判断软件是否运行
    function InitializeUninstall(): Boolean;
    begin
    Result := KDetectSoft('{#MyAppExeName}');
    end;

    // 卸载完成后打开网址
    procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
    var
    ResultCode: Integer;
    begin
    if CurUninstallStep = usPostUninstall then
    begin
        // 在卸载完成后打开网址
        ShellExec('open', '{#MyAppURL}', '', '', SW_SHOWNORMAL, ewNoWait, ResultCode);
    end;
    end;

    // 隐藏安装进度安装路径仅显示文件名
    var
    myLabel: TNewStaticText;
    procedure InitializeWizard();
    begin
    WizardForm.FilenameLabel.Visible := false;
    MyLabel := TNewStaticText.Create(WizardForm.InstallingPage);
    MyLabel.Parent := WizardForm.InstallingPage;
    MyLabel.Top := WizardForm.FilenameLabel.Top;
    MyLabel.Left := WizardForm.FilenameLabel.Left;
    MyLabel.Width := WizardForm.FilenameLabel.Width;
    MyLabel.Visible := True;
    MyLabel.Caption := '';
    end;
    procedure DisplayFileName();
    begin
    MyLabel.Caption := ExtractFileName(CurrentFileName);
    end;

    '''
    )

    # 生成配置文件
    issDir = Path(__file__).parent
    with open(Path(issDir, "InnoSetup.iss"), "w+", encoding="gbk") as f:
        f.write(iss_content)


if __name__ == "__main__":
    getIss()
    print(
        "打包文件生成成功,运行命令(项目根目录下)：package\\exe\\InnoSetup6\\ISCC.exe package\\exe\\InnoSetup.iss"
    )
